<template>
<view class="page">
		<fu-custom :isBack="true" :isBottom="true" bgColor="bg-white">
			<block slot="content">{{edit_id?i18n['编辑地址']:i18n['添加地址']}}</block>
			<!-- #ifndef MP-WEIXIN -->
			<block slot="right">
				<text v-if="edit_id" @click="delAddr" class="text-lg text-black">{{i18n['删除']}}</text>
			</block>
			<!-- #endif -->
		</fu-custom>

		<!-- #ifdef MP-WEIXIN -->
		<view class="float-tag" v-if="edit_id" :style="{top: CustomBar+'px'}" @click="delAddr">
			{{i18n['删除']}}
		</view>
		<!-- #endif -->
		<view class="padding-lr">
			<view class="cu-form-group">
				<view class="title">{{i18n['标签']}}</view>
				<view class="flex-sub">
					<view v-for="(item, index) in serveList" :key="index" class="cu-tag radius"
						:class="item.name == default_serve.name ? (index < 3 ? 'actives' : 'actives radius-left') : 'line-black'"
						@click="changeServe(item)">
						{{ item.name }}
					</view>
					<view v-if="serveList.length == 4" class="cu-tag radius bg-theme text-white fu-ml0 radius-right"
						@click="addServe(serveList[3].name)">{{i18n["编辑"]}}</view>
					<view class="cu-tag line-black radius" @click="addServe()" v-if="serveList.length == 3">+</view>
				</view>
			</view>

			<view class="cu-form-group">
				<view class="title">{{i18n["收货人"]}} <text class="opacity0">人</text></view>
				<view class="flex-sub flex">
					<input type="text" v-model="name" placeholder-class="placeholderClass"
						:placeholder="i18n['收货人']" />
					<view class="flex">
						<view class="text-999" @click="chooseSex('1')">
							<text
								:class="[sex == 1 ? 'cuIcon-roundcheckfill active text-xl' : 'cuIcon-round text-xl']"></text>
							<text :class="{ 'text-666': sex == 1 }" class="margin-left-xs">{{i18n["先生"]}}</text>
						</view>
						<view class="text-999 margin-left" @click="chooseSex('2')">
							<text
								:class="[sex == 2 ? 'cuIcon-roundcheckfill active text-xl' : 'cuIcon-round text-xl']"></text>
							<text :class="{ 'text-666': sex == 2 }" class="margin-left-xs">{{i18n['女士']}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">{{i18n["联系电话"]}}</view>
				<input type="number" maxlength="11" v-model="phone" placeholder-class="placeholderClass"
					:placeholder="i18n['联系电话']" />
				<!-- <text @click="openCode">
					<text class="text-black">+{{prefix}}</text><text class="cuIcon-right"></text>
				</text> -->
			</view>
			<view class="cu-form-group">
				<text class="title">{{i18n["所在地区"]}}</text>
				<view class="flex-sub">
					<view class="flex align-center">
						<input class="flex-sub" type="text" disabled v-model="address" :placeholder="i18n['请选择省市区县、乡镇']"
							@click="showMulLinkageThreePicker" placeholder-class="placeholderClass" />
						<!-- <text class="cuIcon-location" style="font-size: 36rpx; " @click="location"></text> -->
						<text class="cuIcon-right"></text>
					</view>

				</view>
			</view>
			<view class="cu-form-group">
				<textarea class="text-area" type="text" v-model="addressDesc" maxlength="50"
					:placeholder="i18n['请输入详细地址：如道路、门牌号、小区、楼栋号等']" placeholder-class="placeholderClass" />
			</view>

			<view class="cu-form-group">
				<view class="title">{{i18n['设为默认地址']}}</view>
				<switch :class="is_default ? 'checked-green' : ''" class="switch"
					:color="is_default?addRadioColor:addRadioDefaultColor" @change="handleSwitch"
					:checked="is_default ? true : false"></switch>
			</view>
		</view>
		<!-- 表单信息 end -->
		<!-- 服务标签弹框 start -->
		<view v-if="serve_show">
			<view class="serve-mask" @click="serve_show = false"></view>
			<view class="serve-pop flex align-center justify-center padding-lr" :style="{bottom:keyboardheight+'px'}">
				<view class="flex-sub">
					<input type="text" :placeholder="i18n['请填写标签名称（最多5个字）']" v-model='serveKeyword' maxlength="5" focus
						:adjust-position='false' placeholder-class="placeholderServe" class="bg-gray round text-df">
				</view>
				<button class="cu-btn round bg-theme text-white margin-left-sm"
					@click='addServeInfo()'>{{i18n['添加']}}</button>
			</view>
		</view>
		<!-- 服务标签弹框 end -->
		<!-- 底部占位 start -->
		<view class="bottom-status"></view>
		<!-- 底部占位 end -->
		<!-- 提交按钮 start -->
		<view class="bottom-action">
			<button class="cu-btn round btn-lg-theme" @click="sub_sure">{{i18n['保存']}}</button>
		</view>
		<!-- 提交按钮 end -->
		<!-- 国际区号 start -->
		<!-- <fu-area-code ref="areaCode" @change="codeChange"></fu-area-code> -->
		<!-- 国际区号 end -->
		<!-- 地址选择插件 start -->

		<w-picker mode="region" :value="defVal" default-type="label" :confirmColor="themeColor"
			@confirm="onConfirm($event)" ref="region">{{i18n['选择所在地区']}}</w-picker>

		<!-- 地址选择插件 end -->
		<!-- 断网监测 start -->
		<fu-notwork></fu-notwork>
		<!-- 断网监测 end -->
	</view>
</template>

<script>
	import wPicker from '../components/w-picker/w-picker.vue';
	// import fuAreaCode from '../components/fu-area-code/fu-area-code.vue';
	// 高德地图sdk
	import amapFile from '@/libs/amap-wx.js';
	export default {
		computed: {
			// 合并省市区信息字段
			address() {
				return this.province + this.city + this.district;
			},
			themeColor() {
			  return this.$store.state.themeColor
			}
		},
		components: {
			wPicker,
			// fuAreaCode
		},
		data() {
			return {
				addFalg: false, //防连点
				StatusBar: this.StatusBar, // 标题栏高度
				CustomBar: this.CustomBar, // 状态栏高度
				title: '',
				keyboardheight: 0, // 键盘高度
				copyInfo: '', // 复制需要自动识别的地址信息
				serveKeyword: '', // 服务标签关键字
				serve_show: false, // 服务标签弹框
				serveList: [], // 服务标签
				default_serve: {}, // 默认服务标签
				phone: '', // 联系电话
				name: '', // 收货人姓名
				sex: 1, // 性别 1:男 2:女
				is_default: true, // 是否设为默认地址
				edit_id: null, // 是否是修改收货地址
				myAmapFun: null, // 高德地图实例
				province: '', // 省
				city: '', //市
				district: '', //区
				provinceCode: '', // 省 code码
				cityCode: '', //市 code码
				districtCode: '', //区 code码
				addressDesc: '', // 详细地址
				customStyle: {
					backgroundColor: '#cccccc',
					color: '#ffffff'
				}, // 自定义按钮样式
				prefix: '86',
				defVal: [], // 默认地址
				addRadioColor: '#B82441',
				addRadioDefaultColor: '#bfbfbf'
			};
		},
		/**
		 * @description 页面入参
		 * @param {object} options = [id]
		 * @param {string} id = 修改的地址ID
		 */
		onLoad(options) {
			this.title = this.i18n['添加地址']
			// 监听键盘高度
			uni.onKeyboardHeightChange(res => {
				console.log('键盘监听', res);
				this.keyboardheight = res.height;
			});
			// 初始化高德地图SDK,记得换成自己的key
			this.myAmapFun = new amapFile.AMapWX({
				key: 'da1c01509a0dbea0bff1d85d45edc378'
			});
			//如果是修改地址
			if (options.id) {
				this.edit_id = options.id;
				// 换标题文字
				this.title = this.i18n['编辑']
				// 获取要修改的地址信息
				this.get_editAddress();
			} else {
				// 自动定位当前地址
				// this.autoGetLocation();
				// 获取默认标签
				this.getLabelData();
			}
		},
		methods: {
			/**
			 * @description 删除地址
			 * */
			delAddr() {
				this.$util.showModal({
					title: this.i18n['提示'],
					content: this.i18n['是否删除该地址'],
					confirmColor: this.$store.state.themeColor,
					success: (res) => {
						if (res.confirm) {
							this.$api.post(global.apiUrls.postUserAddressDelAddress, {
									address_ids: this.edit_id
								})
								.then(res => {
									console.log(res);
									if (res.data.code == 1) {
										uni.navigateBack();
									} else {
										this.$message.info(res.msg);
									}
								});
						}
					}

				})
			},
			/**
			 * @description 打开选择区号
			 */
			openCode() {
				this.$refs.areaCode.open();
			},
			/**
			 * @description 获取国际区号
			 * @param {String,Number} code 国际区号
			 */
			codeChange(code) {
				this.prefix = code;
				// console.log(code);
			},
			/**
			 * @func 显示区号选择弹框
			 */
			showCountryCodePop() {},
			/**
			 * @func 获取需要智能识别的地址
			 */
			getCopyInfo() {
				console.log(this.copyInfo);
				if (this.copyInfo) {
					// 张三18738978924江苏省扬州市广陵区XX小区X楼xxx室
					console.log(parse(this.copyInfo));
					let info = parse(this.copyInfo);
					this.phone = info.phone ? info.phone : info.mobile;
					this.name = info.name;
					this.province = info.province;
					this.city = info.city;
					this.district = info.area;
					this.addressDesc = info.addr;
					this.$message.info(this.i18n['填写成功，请仔细检查如有错误请手动修改']);
					this.copyInfo = '';
				}
			},
			/**
			 * @description  获取服务标签列表
			 * @param {String} val 回显自定义标签关键词
			 */
			getLabelData(val) {
				this.$api
					.post(global.apiUrls.getLabel, {})
					.then(res => {
						if (res.data.code == 1) {
							console.log('服务标签列表', res.data.data);
							this.serveList = res.data.data
							let serve = uni.getStorageSync('DEFAULT_SERVE');
							// 判断是否为编辑
							if (this.edit_id) {
								this.default_serve = {
									id: 0,
									name: val
								}
								var flag = this.serveList.filter((item) => {
									return item.name == val
								})
								if (flag.length == 0) {
									if (this.default_serve.name) this.serveList.push(this.default_serve);
								}
							} else {
								if (serve && this.serveList != 0) {
									this.default_serve = this.serveList[0]
									this.serveList.push(JSON.parse(serve))
								}
							}
						} else {
							this.$message.info(res.data.msg);
						}
					})
					.catch(err => {
						this.$message.info(err.msg);
					});
			},
			/**
			 * @description  自定义服务标签弹窗显示
			 * @param {String} name 回显自定义标签关键词
			 */
			addServe(name) {
				if (name) {
					this.serveKeyword = name;
				}
				this.serve_show = true; //弹窗显示
			},
			/**
			 * @func 新增服务标签
			 */
			addServeInfo() {
				let val = this.serveKeyword.trim();
				if (val) {
					console.log(this.serveList);
					var flag = this.serveList.filter(item => {
						return item.name == val;
					});
					console.log(flag);
					if (flag.length == 0) {
						this.serve_show = false; // 弹窗隐藏
						let serve = {
							id: 0,
							name: val
						};
						// 存在自定义标签
						if (this.serveList.length > 3) {
							this.serveList[3] = serve;
						} else {
							this.serveList.push(serve);
						}
						this.default_serve = serve;
						if (!this.edit_id) {
							uni.setStorageSync('DEFAULT_SERVE', JSON.stringify(serve));
						}
					} else {
						this.$message.info(this.i18n['标签已存在']);
					}
				} else {
					this.$message.info(this.i18n['请输入内容']);
				}
			},
			/**
			 * @description 切换服务标签
			 * @param {String} item = 服务标签关键字
			 */
			changeServe(item) {
				this.default_serve = item;
			},
			/**
			 * @description 选择性别
			 * @param {String} type = 性别
			 */
			chooseSex(type) {
				this.sex = type;
			},
			/**
			 * @func 获取修改地址信息
			 */
			get_editAddress() {
				this.$api
					.post(global.apiUrls.postUserAddressGetOneAddress, {
						address_id: this.edit_id
					})
					.then(res => {
						console.log(res, '修改的信息');
						if (res.data.code == 1) {
							let data = res.data.data;
							this.name = data.name; // 收货人姓名
							this.phone = data.mobile; // 收货人电话
							this.province = data.province; // 省
							this.city = data.city; // 市
							this.district = data.district; // 区
							this.sex = data.sex; // 性别
							this.addressDesc = data.address; // 详细地址
							this.is_default = data.is_default == '1' ? true : false; // 是否默认
							this.prefix = data.prefix || 86;
							this.sex = data.sex;
							this.defVal = [data.province, data.city, data.district];
							// 服务标签
							this.getLabelData(data.label_name);
						} else {
							this.$message.info(res.data.msg);
						}
					})
					.catch(err => {
						this.$message.info(err.msg);
					});
			},
			/**
			 * @func 显示地址选择弹窗
			 */
			showMulLinkageThreePicker() {
				uni.hideKeyboard();
				this.$refs.region.show();
			},
			/**
			 * @description 地址选择回调
			 * @param {Object} val = 地址信息对象
			 */
			onConfirm(val) {
				this.province = val.obj.province.label;
				this.city = val.obj.city.label;
				this.district = val.obj.area.label;
				this.provinceCode = val.value[0];
				this.cityCode = val.value[1];
				this.districtCode = val.value[2];
			},
			/**
			 * @func 切换是否为默认地址
			 */
			handleSwitch() {
				this.is_default = !this.is_default;
			},
			/**
			 * @func 定位地址
			 */
			location() {
				let _this = this;
				// //#ifdef MP-WEIXIN
				// uni.getSetting({
				// 	success(res) {
				// 		// 获取设置成功
				// 		console.log(res.authSetting, 'getSetting');
				// 		if (!res.authSetting.userLocation) {
				// 			// 如果没开启权限提示打开
				// 			uni.openSetting({
				// 				success(res) {
				// 					// 打开成功，提示获取权限
				// 					console.log(res.authSetting, 'openSetting');
				// 					uni.authorize({
				// 						scope: 'scope.userLocation',
				// 						success(res) {
				// 							_this.chooseLocation();
				// 						},
				// 						fail(res) {
				// 							console.log(res);
				// 							this.$message.info(this.i18n['打开权限失败']);
				// 						}
				// 					});
				// 				}
				// 			});
				// 		} else {
				// 			_this.chooseLocation();
				// 		}
				// 	}
				// });
				// //#endif
				this.chooseLocation();
			},
			/**
			 * @func 地图选点
			 */
			chooseLocation() {
				uni.chooseLocation({
					success: res => {
						console.log(res, '地图');
						this.myAmapFun.getRegeo({
							location: res.longitude + ',' + res.latitude,
							success: data => {
								//成功回调
								console.log('sdk回调', data);
								let regeoData = data[0].regeocodeData.addressComponent;
								this.province = regeoData.province;
								this.city = Array.isArray(regeoData.city) && regeoData.city
									.length == 0 ? regeoData.province : regeoData.city;
								this.district = regeoData.district;
								this.addressDesc = res.address + res.name;
								this.provinceCode = regeoData.adcode.substr(0, 2) + '0000';
								this.cityCode = regeoData.adcode.substr(0, 4) + '00';
								this.districtCode = regeoData.adcode + '';
								console.log(this.province + this.city + this.district + this
									.addressDesc);
							},
							fail: info => {
								//失败回调
								console.log(info);
							}
						});
					}
				});
			},
			/**
			 * @func 自动定位
			 */
			autoGetLocation() {
				console.log('auto ');
				uni.getLocation({
					geocode: true,
					success: adr => {
						console.log(adr);
						// #ifdef APP-PLUS
						let address = adr.address;
						this.province = address.province;
						this.city = Array.isArray(regeoData.city) && regeoData.city.length == 0 ? regeoData
							.province : regeoData.city;
						this.district = address.district;
						this.addressDesc = address.street + address.streetNum + address.poiName;
						// #endif
						// #ifndef APP-PLUS
						this.myAmapFun.getRegeo({
							location: adr.longitude + ',' + adr.latitude,
							success: data => {
								//成功回调
								console.log('sdk回调', data);
								let regeoData = data[0].regeocodeData.addressComponent;
								this.province = regeoData.province;
								this.city = Array.isArray(regeoData.city) && regeoData.city
									.length == 0 ? regeoData.province : regeoData.city;
								this.district = regeoData.district;
								this.addressDesc = data[0].desc;
								this.provinceCode = regeoData.adcode.substr(0, 2) + '0000';
								this.cityCode = regeoData.adcode.substr(0, 4) + '00';
								this.districtCode = regeoData.adcode + '';
								console.log(this.province + this.city + this.district + this
									.addressDesc);
							},
							fail: info => {
								//失败回调
								console.log(info);
							}
						});
						// #endif
					}
				});
			},
			/**
			 * @func 提交表单
			 */
			sub_sure() {
				if (this.addFalg) return this.$message.info("点击过快，请稍后再试")
				this.addFalg = true
				let that = this
				setTimeout(() => {
					that.addFalg = false
				}, 2000)
				// 表单验证
				if (this.name.trim() == '') {
					this.$message.info(this.i18n['请输入收货人姓名']);
					this.name = '';
					return false;
				}
				if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phone)) {
					let text = !this.phone ? this.i18n['请输入手机号'] : this.i18n['手机号格式不正确'];
					this.$message.info(text);
					return false;
				}
				if (this.address.trim() == '') {
					this.$message.info(this.i18n['地区不能为空']);
					return false;
				}
				if (this.addressDesc.trim() == '') {
					this.$message.info(this.i18n['详细地址不能为空']);
					this.addressDesc = '';
					return false;
				}
				if (!this.default_serve.name) {
					this.$message.info('请选择一个标签');
					return false;
				}
				let data = {
					name: this.name, // 收货人姓名
					mobile: this.phone, // 收货人手机
					is_default: this.is_default ? '1' : '0', // 是否默认地址
					address: this.addressDesc, // 详细地址
					sex: this.sex,
					province: this.province, // 省
					city: this.city, // 市
					district: this.district, // 区
					prefix: this.prefix,
					sex: this.sex,
					provinceCode: this.provinceCode, // 省 code码
					cityCode: this.cityCode, //市 code码
					districtCode: this.districtCode, //区 code码
				};
				if (this.default_serve.name) {
					data.label_name = this.default_serve.name;
				}
				// 判断提交的接口
				let url = global.apiUrls.postUserAddressAddAddress;
				if (this.edit_id) {
					data.address_id = this.edit_id;
					url = global.apiUrls.postUserAddressEditAddress;
				}
				// 提交请求
				this.$api
					.post(url, data)
					.then(res => {
						console.log(res, '添加/编辑成功');
						if (res.statusCode == 200 && res.data.code == 1) {
							this.$message.info(this.i18n['保存成功']);
							uni.$emit('refreshAddress')
							setTimeout(() => {
								uni.navigateBack();
							}, 800);
						} else {
							this.$message.info(res.data.msg);
						}
					})
					.catch(err => {
						console.log('err: ', err);
					});
			},
			/**
			 * @func 清除手机号
			 */
			clear() {
				this.phone = '';
			}
		}
	};
</script>
<style lang="scss" scoped>
.page {
		min-height: 100vh;
		background: #ffffff;
	}
	.opacity0 {
		opacity: 0;
	}
	.cu-form-group {
		padding-left: 0 !important;
		padding-right: 0 !important;
	}

	.cu-form-group uni-input {
		color: #333 !important;
	}

	.icon-location {
		width: 28rpx;
		height: 35rpx;
	}

	.float-tag {
		width: 100%;
		height: 60rpx;
		text-align: right;
		line-height: 60rpx;
		font-size: 28rpx;
		padding: 0 32rpx;
		position: sticky;
		z-index: 999;
		background-color: #ffffff;
	}

	.text-area {
		width: 100%;
		height: 200rpx !important;
		line-height: 25px;
		background-color: #f6f6f6;
		padding: 20rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
	}

	.placeholderClass {
		font-size: 32rpx;
		color: #bfbfbf;
	}

	.active {
		color: $theme !important;
	}

	.switch {
		transform: scale(0.9);
	}

	switch::before,
	switch::after {
		content: '';
	}

	// 底部按钮
	.bottom-status {
		height: 156rpx;
		height: calc(156rpx + constant(safe-area-inset-bottom));
		height: calc(156rpx + env(safe-area-inset-bottom));
	}

	.bottom-action {
		position: fixed;
		right: 32rpx;
		left: 32rpx;
		bottom: 56rpx;
		bottom: calc(56rpx + constant(safe-area-inset-bottom));
		bottom: calc(56rpx + env(safe-area-inset-bottom));
		display: flex;
	}

	// --------------  添加标签 样式  --------------
	.serve-mask {
		background: rgba(0, 0, 0, 0.3);
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 9999;
	}

	.serve-pop {
		height: 100rpx;
		position: fixed;
		bottom: 0;
		width: 100%;
		background-color: #ffffff;
		z-index: 99999;

		input {
			height: 66rpx;
			background: #f6f7f9;
			text-indent: 1em;
		}
	}

	.radius-left {
		border-top-left-radius: 20rpx;
		border-bottom-left-radius: 20rpx;
	}

	.radius-right {
		border-top-right-radius: 20rpx;
		border-bottom-right-radius: 20rpx;
	}

	// 粘贴板智能识别 样式,需要时打开
	.cell2 {
		font-size: 32upx;
		align-items: center;
		padding: 32rpx 0;
		border-bottom: 1px solid #f5f5f7;

		.btn-copy {
			overflow: hidden;

			button {
				width: 130rpx;
				height: 56rpx;
				background: #FF6464;
				border-radius: 28rpx;
				color: #fff;
				font-size: 24rpx;
				float: right;
			}
		}
	}
	
	.actives{
		background: #FF9D00!important;
		color: #ffffff;
	}
</style>
